import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

interface SerializableNote {
  id: number
  title: string
  content: string
  createdAt: string
  updatedAt: string
}

// Custom APIs for renderer
const api = {
  // 切换窗口置顶
  toggleAlwaysOnTop: () => ipcRenderer.invoke('toggle-always-on-top'),

  // 获取置顶状态
  getAlwaysOnTop: () => ipcRenderer.invoke('get-always-on-top'),

  // 监听置顶状态变化
  onAlwaysOnTopChanged: (callback: (isAlwaysOnTop: boolean) => void) => {
    ipcRenderer.on('always-on-top-changed', (_, isAlwaysOnTop) => {
      callback(isAlwaysOnTop)
    })
  },

  // 移除监听器
  removeAlwaysOnTopListener: () => {
    ipcRenderer.removeAllListeners('always-on-top-changed')
  },

  // 创建脱出窗口
  createDetachedWindow: (note: SerializableNote) =>
    ipcRenderer.invoke('create-detached-window', note),

  // 获取脱出note数据
  getDetachedNote: () => ipcRenderer.invoke('get-detached-note'),

  // 更新脱出窗口中的note数据
  updateDetachedNote: (note: SerializableNote) => ipcRenderer.invoke('update-detached-note', note),

  // 监听note返回事件
  onNoteReturned: (callback: (note: SerializableNote) => void) => {
    ipcRenderer.on('note-returned', (_, note) => {
      callback(note)
    })
  },

  // 移除note返回监听器
  removeNoteReturnedListener: () => {
    ipcRenderer.removeAllListeners('note-returned')
  },

  // 脱出窗口置顶功能
  toggleDetachedWindowAlwaysOnTop: () => ipcRenderer.invoke('toggle-detached-window-always-on-top'),

  // 获取脱出窗口置顶状态
  getDetachedWindowAlwaysOnTop: () => ipcRenderer.invoke('get-detached-window-always-on-top'),

  // 监听脱出窗口置顶状态变化
  onDetachedWindowAlwaysOnTopChanged: (callback: (isAlwaysOnTop: boolean) => void) => {
    ipcRenderer.on('detached-window-always-on-top-changed', (_, isAlwaysOnTop) => {
      callback(isAlwaysOnTop)
    })
  },

  // 移除脱出窗口置顶监听器
  removeDetachedWindowAlwaysOnTopListener: () => {
    ipcRenderer.removeAllListeners('detached-window-always-on-top-changed')
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
